package com.jingjing.control.note;

import com.jingjing.model.note.Note;
import com.jingjing.model.note.NoteBook;
import com.jingjing.model.user.LoginUser;
import com.jingjing.model.user.User;
import com.jingjing.service.note.NoteBookService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.util.*;

/**
 * @program: jingjing
 * @description: 笔记本相关操作
 * @author: 何伟
 * @create: 2019-04-10 17:09
 **/
@Controller
public class NoteBookController {

    Logger logger = LoggerFactory.getLogger(this.getClass());
    @Autowired
    private NoteBookService noteBookService;

    @RequestMapping("addNoteBook")
    @ResponseBody
    public Map addNoteBook(String title, String description, HttpSession session) {
        User user = (User) session.getAttribute("user");
        Map<String, String> msg = new HashMap<>();
        msg.put("info", "添加成功！");
        NoteBook noteBook = new NoteBook();

        noteBook.setTitle(title);
        noteBook.setDescription(description);
        noteBook.setUserId(user.getId());
        noteBook.setCreateDate(new Date());

        try {
            noteBookService.addNoteBook(noteBook);
        } catch (Exception e) {
            logger.error("添加笔记本出错，详情：" + e.getMessage());
            msg.put("info", "程序错误！");
        }

        return msg;

    }

    @RequestMapping("notebooks")
    public String noteBooks(HttpSession session, ModelMap modelMap) {
        List<NoteBook> noteBooks = new ArrayList<NoteBook>();
        if (null == session) {
            return "notebook-list";
        }
        User user = (User) session.getAttribute("user");
        noteBooks = noteBookService.getUserNoteBooks(user.getId());

        modelMap.addAttribute("notebooks", noteBooks);
        return "notebook-list";
    }

    @RequestMapping("removenotebook")
    public String removeNoteBook(HttpSession session, Long bookId,ModelMap modelMap) {

        int result=noteBookService.deleteNoteBook(bookId);

        if (result<0){
            modelMap.addAttribute("ErrorCode","500");
            modelMap.addAttribute("ErrorTitle","服务器异常");
            modelMap.addAttribute("ErrorCode","删除笔记本失败！");
            return "jingjing-error.html";
        }
        return "redirect:notebooks";
    }

}
